package main.bytedance.checkInclusion;

/**
 * @author kejl
 * @version test
 * @date 2020/5/31 8:11
 */
public class CheckInclusion {


    public static void main(String[] args) {
        new CheckInclusion().checkInclusion("abcs","acabcs");
    }

    public boolean checkInclusion(String s1, String s2) {
        if (s1.length() > s2.length())
            return false;
        int[] s1map = new int[26];
        int[] s2map = new int[26];
        //前s1字符串的长度进行转换，字符相减得到下标,所有字符出现的次数，此时s1是固定的，s2就是获取s1同样长度的。
        for (int i = 0; i < s1.length(); i++) {
            s1map[s1.charAt(i) - 'a']++;
            s2map[s2.charAt(i) - 'a']++;
        }
        int count = 0;
        //验证是否完全匹配
        for (int i = 0; i < 26; i++) {
            if (s1map[i] == s2map[i]) {
                count++;
            }
        }
        for (int i = 0; i < s2.length() - s1.length(); i++) {
            //滑动开始了：s2只需要s1那些的下标，以s1为基准，往后挪一个则需要把最前面的-1，然后最后面的加1
            //最后的结果就是加减之后变成了和s1范围内的
            int r = s2.charAt(i + s1.length()) - 'a', l = s2.charAt(i) - 'a';
            if (count == 26)
                return true;
            s2map[r]++;//s2中s1之后的字符数量+1
            if (s2map[r] == s1map[r])//匹配到了则count+1
                count++;
            else if (s2map[r] == s1map[r] + 1)//要匹配的数量（与s1整体相比）出现的多了count-1
                count--;
            s2map[l]--;//s2中s1的字符数量-1，把左侧移出去
            if (s2map[l] == s1map[l])//
                count++;
            else if (s2map[l] == s1map[l] - 1)
                count--;
        }
        return count == 26;


    }
}
